package com.g.base.help.glide

import com.bumptech.glide.load.engine.cache.DiskCache
import com.g.base.appContent
import com.g.base.help.tryCatch
import java.io.File
import java.math.BigDecimal


object GlideChaceHelp {
    //格式化单位
    private fun getFormatSize(size: Long): String {
        val kiloByte = size / 1024
        if (kiloByte < 1) {
            return size.toString() + "Byte"
        }
        val megaByte = kiloByte / 1024
        if (megaByte < 1) {
            val result1 = BigDecimal(kiloByte)
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB"
        }
        val gigaByte = megaByte / 1024
        if (gigaByte < 1) {
            val result2 = BigDecimal(megaByte)
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB"
        }
        val teraBytes = gigaByte / 1024
        if (teraBytes < 1) {
            val result3 = BigDecimal(gigaByte)
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB"
        }
        val result4 = BigDecimal(teraBytes)
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB"
    }

    // 获取指定文件夹内所有文件大小的和
    private fun getFolderSize(file: File): Long {
        var size: Long = 0
        tryCatch {
            val fileList = file.listFiles()
            for (aFileList in fileList) {
                size += if (aFileList.isDirectory) {
                    getFolderSize(aFileList)
                } else {
                    aFileList.length()
                }
            }
        }
        return size
    }

    fun getCacheSize(): String {
        return getFormatSize(getFolderSize(File("${appContent.cacheDir}/${DiskCache.Factory.DEFAULT_DISK_CACHE_DIR}")))
    }
}